package zcw.com.lib_leet_code;

/**
 * Created by 朱城委 on 2021/7/15.<br><br>
 *
 * 字符串相加
 */
public class Topic415 {

    public static void main(String[] args) {
        Topic415 instance = new Topic415();

        System.out.println(instance.addStrings("11", "123"));
        System.out.println(instance.addStrings("456", "77"));
        System.out.println(instance.addStrings("0", "0"));
        System.out.println(instance.addStrings("1", "9"));
    }

    public String addStrings(String num1, String num2) {
        int start1 = num1.length() - 1;
        int start2 = num2.length() - 1;

        int carry = 0;
        char[] array1 = num1.toCharArray();
        char[] array2 = num2.toCharArray();
        StringBuilder builder = new StringBuilder();
        while (start1 >= 0 || start2 >= 0) {
            int digit1 = start1 >= 0 ? array1[start1] - '0' : 0;
            int digit2 = start2 >= 0 ? array2[start2] - '0' : 0;
            int temp = digit1 + digit2 + carry;
            if(temp > 9) {
                temp = temp - 10;
                carry = 1;
            }
            else {
                carry = 0;
            }

            builder.append(temp);
            start1--;
            start2--;
        }

        if(carry == 1) {
            builder.append(carry);
        }

        return builder.reverse().toString();
    }
}
